# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/8/14 14:06
# File      : ReadYaml.py
# explain   : 文件说明


import yaml
from yaml import Loader
import os
import pathlib


def get_yml_data(file_path, file_name, data_name=None):
    """
    module  yml文件所在模块下
    """
    base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    data_file_path = os.path.join(base_path, f'TestCase/{file_path}', f'{file_name}.yaml')
    # data_file_path = os.path.join(base_path, f'TestCase/Sync/', f'{file_name}.yaml')
    file_data = pathlib.Path(data_file_path).read_text()

    return (
        yaml.load(file_data, Loader=Loader).get(data_name)
        if data_name
        else yaml.load(file_data, Loader=Loader, )
    )


def revise_yml_data(file_path, file_name, dict_key, second_key, info_data, end_key=None):
    base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    data_file_path = os.path.join(base_path, f'TestCase/{file_path}/', f'{file_name}.yaml')
    # data_file_path = os.path.join(base_path, f'Data/Sync/', f'{file_name}.yaml')

    with open(data_file_path, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
        file.close()

    with open(data_file_path, 'w', encoding='utf-8') as file:
        if end_key:
            data[dict_key][0][second_key][end_key] = info_data
            yaml.dump(data, file, allow_unicode=True)
            file.close()
        else:
            data[dict_key][second_key] = info_data
            yaml.dump(data, file, allow_unicode=True)
            file.close()


if __name__ == '__main__':
    print(get_yml_data('Action', 'token', 'get_token')[0])
    revise_yml_data('Action','userinfo','userinfo','palayod',12131,'access_token')
